package com.itheima.tanhua.service;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.autoconfig.template.HuanXinTemplate;
import com.itheima.tanhua.api.db.QuestionApi;
import com.itheima.tanhua.api.db.UserApi;
import com.itheima.tanhua.api.mongodb.BaiduLocationApi;
import com.itheima.tanhua.api.mongodb.FriendApi;
import com.itheima.tanhua.api.mongodb.UserLikeApi;
import com.itheima.tanhua.enums.Constants;
import com.itheima.tanhua.pojo.db.Question;
import com.itheima.tanhua.pojo.db.User;
import com.itheima.tanhua.pojo.db.UserInfo;
import com.itheima.tanhua.pojo.mongo.RecommendUser;
import com.itheima.tanhua.api.db.UserInfoApi;
import com.itheima.tanhua.api.mongodb.RecommendApi;
import com.itheima.tanhua.pojo.mongo.UserLocation;
import com.itheima.tanhua.vo.HuanxinUserVo;
import com.itheima.tanhua.vo.NearUserVo;
import com.itheima.tanhua.vo.PageResult;
import com.itheima.tanhua.vo.TodayBestVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class RecommendService {

    @DubboReference
    private RecommendApi recommendService;
    @DubboReference
    private UserInfoApi userInfoService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @DubboReference
    private UserApi userApi;
    @DubboReference
    private QuestionApi questionApi;
    @Autowired
    private HuanXinTemplate huanXinTemplate;
    @DubboReference
    private UserLikeApi userLikeApi;
    @DubboReference
    private FriendApi friendApi;
    @Autowired
    private MessagesService messagesService;
    @DubboReference
    private BaiduLocationApi baiduLocationApi;

    /**
     * 获取今日佳人的具体信息和数据 todayBestVo来放置
     * @return
     */
    public TodayBestVo todayBest() {

        String redisKey = "CHECK_ID";
        String uid = stringRedisTemplate.opsForValue().get(redisKey);
        //2.通过现在的用户id远程调用mongo 获取进入缘分值的最高值的一条数据 对象
        RecommendUser recommendUser = recommendService.getByToUserId(Convert.toLong(uid));
        Long userId = recommendUser.getUserId();
        //3.通过获取的UserId 去通过Mysql查询该id的数据
        UserInfo userInfo = userInfoService.selectById(userId);
        //创建Vo的对象
        TodayBestVo todayBestVo = new TodayBestVo();
        //将userInfo中的数据复制到后者中
         BeanUtil.copyProperties(userInfo,todayBestVo);
        //Vo中有一个字段
        todayBestVo.setTags(StrUtil.split(userInfo.getTags(), ","));
        todayBestVo.setFateValue(Convert.toInt(recommendUser.getScore()));
        return todayBestVo;
    }

    /**
     * 获取今日推荐的所有数据
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult recommendation(Integer page, Integer pagesize) {
        //从redis中获取id
        String redisKey = "CHECK_ID";
        String uid = stringRedisTemplate.opsForValue().get(redisKey);

        //创建今日佳人的信息的集合
        List<TodayBestVo> list = new ArrayList<>();

        //根据登录用户的id 查询此用户的所有推荐数据   使用mongodb
        List<RecommendUser> recommendUsers = recommendService.getData(Convert.toLong(uid));
        for (RecommendUser recommendUser : recommendUsers) {
            Long userId = recommendUser.getUserId();
            //3.通过获取的UserId 去通过Mysql查询该id的数据
            UserInfo userInfo = userInfoService.selectById(userId);
            //创建Vo的对象
            TodayBestVo todayBestVo = new TodayBestVo();
            //将userInfo中的数据复制到后者中
            BeanUtil.copyProperties(userInfo,todayBestVo);
            //Vo中有一个字段
            todayBestVo.setTags(StrUtil.split(userInfo.getTags(), ","));
            todayBestVo.setFateValue(Convert.toInt(recommendUser.getScore()));
            list.add(todayBestVo);
        }
        return new PageResult(pagesize, page, list);
    }

    /**
     * 通过id获取佳人的信息
     * @param id
     * @return
     */
    public TodayBestVo personalInfo(Long id) {
        //获取当前用户的id uid
        String redisKey = "CHECK_ID";
        Long uid = Convert.toLong(stringRedisTemplate.opsForValue().get(redisKey));

        TodayBestVo todayBestVo=new TodayBestVo();
        //通过id查询userInfo
        UserInfo userInfo = userInfoService.selectById(id);
        //处理数据,返回数据vo
        BeanUtil.copyProperties(userInfo,todayBestVo);
        todayBestVo.setTags(StrUtil.split(userInfo.getTags(), ","));
        //需要获取缘分值
        RecommendUser recommendUser= recommendService.findByuId(id,uid);
        todayBestVo.setFateValue(Convert.toInt(recommendUser.getScore()));
        return todayBestVo;
    }

    //通过id查询到huanxin的信息
    public HuanxinUserVo findHuanxinById() {
        //获取uid
        String redisKey = "CHECK_ID";
        Long uid = Convert.toLong(stringRedisTemplate.opsForValue().get(redisKey));
        //通过uid 查询用户信息
        User user = userApi.findById(uid);
        //封装数据vo
        HuanxinUserVo vo=new HuanxinUserVo();
        vo.setUsername(user.getHxUser());
        vo.setPassword(user.getHxPassword());
        return vo;
    }

    //查询陌生人的问题
    public String strangerQuestions(Long userId) {
     //根据前端传来的用户id 去获取用户信息
        Question question = questionApi.findByUserId(userId);
        if (ObjectUtil.isEmpty(question)){
            //是空的对象
            return "我喜欢苹果,你呢?";
        }
        return question.getTxt();
    }

    //回复陌生人的问题
    public void responseQuestions(Map<String, String> pararm) {
        //获取用户的id  获取回复的值
        String userId = pararm.get("userId");
        String reply = pararm.get("reply");
        //获取当前用户的uid
        String redisKey = "CHECK_ID";
        Long uid = Convert.toLong(stringRedisTemplate.opsForValue().get(redisKey));
        UserInfo userInfo = userInfoService.selectById(uid);
        //构建回复的消息格式   昵称
        Map map=new HashMap();
        map.put("userId",Convert.toLong(uid));
        map.put("huanXinId",Constants.HX_USER_PREFIX+uid);
        map.put("nickname",userInfo.getNickname());
        map.put("strangerQuestions",strangerQuestions(Convert.toLong(userId)));
        map.put("reply",reply);
        String Message = JSON.toJSONString(map);
        //调用
        Boolean aBoolean = huanXinTemplate.sendMsg(Constants.HX_USER_PREFIX + userId, Message);
        //1.接受方的环信id 2.消息
        if (!aBoolean){
            //
            throw new RuntimeException("消息发送失败");
        }
    }


    //探花的推荐列表
    public List<TodayBestVo> cards() {
        //通过当前用户的id查询探花的推荐列表,限制一个数量为10
        String redisKey = "CHECK_ID";
        Long uid = Convert.toLong(stringRedisTemplate.opsForValue().get(redisKey));
        List<RecommendUser> list = recommendService.findAll(uid, 10);
        if (CollUtil.isEmpty(list)){
            //list为空的时候  即没有推荐的对象
            throw  new RuntimeException("此用户没有推荐的佳人信息");
        }
        //获取推荐佳人的id的集合
        List<Long> ids = CollUtil.getFieldValues(list, "toUserId",Long.class);
        //通过ids查询用户的详细信息
      List<TodayBestVo> todayBestVoList=new ArrayList<>();
        for (Long id : ids) {
            UserInfo userInfo = userInfoService.selectById(id);
            TodayBestVo todayBestVo=new TodayBestVo();
            BeanUtil.copyProperties(userInfo,todayBestVo);
            todayBestVo.setTags(userInfo.getTags().split(","));
            todayBestVoList.add(todayBestVo);
        }
        return todayBestVoList;
    }




    //设置这位佳人的状态为喜欢  在userlike表中
    public void setLove(Long id) {

        String redisKey = "CHECK_ID";
        Long uid = Convert.toLong(stringRedisTemplate.opsForValue().get(redisKey));
        //加入到userlike的表格中
        boolean flag = userLikeApi.saveLove(id, uid, "true");
        if (!flag){
            //添加失败
            throw new RuntimeException("userLike 添加喜欢数据失败");
        }
        //TODO 写入redis中删除不喜欢,添加喜欢数据
        //判断是否双向喜欢,如果双向喜欢,添加好友 否则,不添加好友
        if (userLikeApi.isLike(id,uid,"true")){
            //双向喜欢  添加好友
            messagesService.contacts(id);
        }
    }
    //设置这位佳人的状态为不喜欢  在userlike表中
    public void setUnLove(Long likeUserId) {
        //获取当前用户的uid
        String redisKey = "CHECK_ID";
        Long uid = Convert.toLong(stringRedisTemplate.opsForValue().get(redisKey));

        //添加 不喜欢的数据到userLike的表格
        boolean flag = userLikeApi.saveLove(likeUserId, uid, "false");
        if (!flag){
            //添加失败
            throw new RuntimeException("userLike 添加不喜欢数据失败");
        }
        //TODO 写入redis中删除不喜欢,添加喜欢数据

        if (userLikeApi.isLike(likeUserId,uid,"false")){

            //删除用户在环信中的好友关系
            huanXinTemplate.deleteContact(uid.toString(),likeUserId.toString());
            //双向喜欢  现在是添加为不喜欢  friend中的数据删除
            friendApi.delete(uid,likeUserId);
        }
    }

    //搜素附近的用户
    public List<NearUserVo> search(String gender, String distance) {
       //获取当前用户的uid
        String redisKey = "CHECK_ID";
        Long uid = Convert.toLong(stringRedisTemplate.opsForValue().get(redisKey));
       //通过uid 获取当前的圆心位置
//         UserLocation nowLocation = baiduLocationApi.findNowLocation(uid);
      List<Long> userIds= baiduLocationApi.queryNearUser(uid,Convert.toDouble(distance));

        return null;
    }
}
